package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleDao roleDao;

    @Override
    public void edit(Role role, Integer[] permissionIds, Integer[] menuIds) {
        Integer roleId = role.getId();
        //先清理关系（中间关系表），在添加关联关系
        //删除角色权限信息
        roleDao.deleteRP(roleId);
        //删除角色菜单信息
        roleDao.deleteRM(roleId);
        //重新添加关系
        roleDao.edit(role);
        roleDao.setRoleAndPermission(roleId,permissionIds);
        roleDao.setRoleAndMenu(roleId,menuIds);

    }

    @Override
    public void add(Role role, Integer[] permissionIds, Integer[] menuIds) {
        roleDao.add(role);



        Integer id = role.getId();
        roleDao.setRoleAndPermission(id,permissionIds);
        roleDao.setRoleAndMenu(id,menuIds);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//页码
        Integer pageSize = queryPageBean.getPageSize();//每页条数
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于分页插件
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = roleDao.findByCondition(queryString);
        long total = page.getTotal();   //MyBatis第二天
        List<CheckGroup> result = page.getResult();
        PageResult pageResult = new PageResult(total, result);
        return pageResult;


    }


    //按id查询角色信息，用于编辑数据回显
    @Override
    public Role findByID(Integer id) {
        Role role = roleDao.findByID(id);
        return role;
    }

    //按id查询权限信息，用于编辑数据回显
    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        List<Integer> permissions = roleDao.findPermissionIdsByRoleId(id);

        return permissions;
    }
    //按id查询菜单信息，用于编辑数据回显
    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {
        List<Integer> menus = roleDao.findMenuIdsByRoleId(id);
        return menus;
    }

    @Override
    public void delete(Integer id) {
        roleDao.deleteRP(id);
        roleDao.deleteRM(id);
        roleDao.deleteR(id);

    }

    public List<Role> findAll() {
        return roleDao.findAll();
    }

}
